package com.hutou.chuangke.activity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.hutou.chuangke.Bean.CollBean;
import com.hutou.chuangke.Bean.SoundBean;
import com.hutou.chuangke.MainApplication;
import com.hutou.chuangke.R;
import com.hutou.chuangke.adapter.CommentAdapter;
import com.hutou.chuangke.adapter.inteface.CommentOnclicListener;
import com.hutou.chuangke.androidbug.AndroidBug5497Workaround;
import com.hutou.chuangke.dialog.NetDailog;
import com.hutou.chuangke.net.HttpUtil;
import com.hutou.chuangke.net.RequestThreadPool;
import com.hutou.chuangke.net.http.HttpUrl;
import com.hutou.chuangke.net.http.User;
import com.hutou.chuangke.uitl.CommonUtils;
import com.hutou.chuangke.widget.DividerItemDecoration;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;

/**
 * Created by Administrator on 2017/5/11.
 * 音乐评论
 */

public class MusicCommentActivity extends BaseActivity implements View.OnClickListener {
    Toolbar toolbar;
    private boolean fullscreen = false;//全屏/窗口播放切换标志
    private Context mContext;
    private int actiobarhei;
    private SoundBean bean;
    private RecyclerView recyclerviewew;
    private Button send_bt;
    private EditText colle_et;
    private LinearLayoutManager manger;
    private ArrayList<CollBean> mData = new ArrayList<>();
    private String strcoll;//评论内容
    private CommentAdapter adapter;
    LoadCollListInfo loadCollListInfo;
    RequestSend requestSend;
    RequestReply requestReply;
    NetDailog netDailog;
    private String colleid;//评论id 用于回复
    private String colluserid;//评论者id
    private boolean isReply;//是否为回复状态
    private ImageView title_iv;
    private TextView title_name,title_singer;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_comment);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        mContext = MusicCommentActivity.this;
        init();
        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        AndroidBug5497Workaround.assistActivity(this);
    }

    private void init() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setPadding(0, CommonUtils.getStatusHeight(mContext), 0, 0);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setHomeAsUpIndicator(R.drawable.actionbar_back);
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setTitle("评论");
        actiobarhei = toolbar.getHeight();
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        showQuickControl(false);
        adapter = new CommentAdapter(mContext);
        netDailog = new NetDailog(mContext);
        recyclerviewew = (RecyclerView) findViewById(R.id.recyclerviewew);
        manger = new LinearLayoutManager(mContext);
        recyclerviewew.setLayoutManager(manger);
        recyclerviewew.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL_LIST));
        recyclerviewew.setAdapter(adapter);
        send_bt = (Button) findViewById(R.id.send_bt);
        send_bt.setOnClickListener(this);
        colle_et = (EditText) findViewById(R.id.colle_et);
        adapter.setonItemListener(new CommentOnclicListener() {
            @Override
            public void onItemClick(View view, int position) {
                isReply = true;
                colle_et.setHint("回复："+mData.get(position).getSinger());
                colleid = mData.get(position).getId();
                colluserid = mData.get(position).getTageruserid();
                Toast.makeText(mContext,"点击id="+mData.get(position).getId()+
                        "评论者id="+mData.get(position).getTageruserid(),Toast.LENGTH_SHORT).show();
            }
        });
        title_iv = (ImageView) findViewById(R.id.title_iv);
        title_name = (TextView) findViewById(R.id.title_name);
        title_singer = (TextView) findViewById(R.id.title_singer);
    }


    private void initData() {
        Intent intent = getIntent();
        bean = (SoundBean) intent.getSerializableExtra("SoundBean");

        if(bean != null){
            loadCollListInfo = new LoadCollListInfo();
            loadCollListInfo.execute(bean.getId());
        }
        title_name.setText(bean.getSoundname());
        title_singer.setText(bean.getSinger());
        ImageLoader.getInstance().displayImage(bean.getSoundurlimg(), title_iv);
    }

    @Override
    public void onClick(View view) {
        if(view == send_bt){
            strcoll = colle_et.getText().toString();
            if(strcoll.equals("")){
                Toast.makeText(mContext,"请填写评论",Toast.LENGTH_SHORT).show();
                return;
            }
            if(isReply) {//是否在回复状态
                requestReply = new RequestReply();
//                requestReply.execute(bean.getId());
                requestReply.execute(bean.getId(),colluserid,colleid);
            }else{
                requestSend = new RequestSend();
                requestSend.execute(bean.getId());
            }


        }
    }
    /***
     * 回复评论
     * params[0] 音乐id
     * params[1] 评论者的id
     * params[2] 回复数据id
     * */
    class RequestReply extends AsyncTask<String,Void,Boolean> {

        @Override
        protected Boolean doInBackground(String... params) {
            try{
                JsonObject jsonObject = HttpUtil.getResposeJsonObject(HttpUrl.GET_TO_HF,
                        User.getToHf(params[0],"2",strcoll,params[1],MainApplication.id,params[2]));
                String flag = jsonObject.get("flag").getAsString();
                if(flag.equals("1")){
                    return true;
                }
                return false;
            }catch(Exception e){
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean comlete) {
            if(comlete){
                isReply = false;
                Toast.makeText(mContext,"回复成功",Toast.LENGTH_SHORT).show();
                loadCollListInfo = new LoadCollListInfo();
                loadCollListInfo.execute(bean.getId()+"");
                colle_et.setText("");
                colle_et.setHint("");
                MoveToPosition(manger,recyclerviewew,0);
                closeInputMethod();
            }else{
                Toast.makeText(mContext,"回复失败",Toast.LENGTH_SHORT).show();
            }
        }

        public void cancleTask(){
            cancel(true);
            RequestThreadPool.finish();
        }
    }

    /***
     * 请求评论
     * */
    class RequestSend extends AsyncTask<String,Void,Boolean> {

        @Override
        protected Boolean doInBackground(String... params) {
            try{
                JsonObject jsonObject = HttpUtil.getResposeJsonObject(HttpUrl.GET_TO_CT,
                        User.getToCt(params[0],"2",strcoll, MainApplication.id));
                String flag = jsonObject.get("flag").getAsString();
                if(flag.equals("1")){
                    return true;
                }
                return false;
            }catch(Exception e){
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean comlete) {
            if(comlete){
                Toast.makeText(mContext,"评论成功",Toast.LENGTH_SHORT).show();
                loadCollListInfo = new LoadCollListInfo();
                loadCollListInfo.execute(bean.getId()+"");
                colle_et.setText("");
                MoveToPosition(manger,recyclerviewew,0);
                closeInputMethod();
            }else{
                Toast.makeText(mContext,"评论失败",Toast.LENGTH_SHORT).show();
            }
        }

        public void cancleTask(){
            cancel(true);
            RequestThreadPool.finish();
        }
    }

    private void closeInputMethod(){
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }
    /**
     * RecyclerView 移动到当前位置，
     *
     * @param manager   设置RecyclerView对应的manager
     * @param mRecyclerView  当前的RecyclerView
     * @param n  要跳转的位置
     */
    public static void MoveToPosition(LinearLayoutManager manager, RecyclerView mRecyclerView, int n) {


        int firstItem = manager.findFirstVisibleItemPosition();
        int lastItem = manager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            mRecyclerView.scrollToPosition(n);
        } else if (n <= lastItem) {
            int top = mRecyclerView.getChildAt(n - firstItem).getTop();
            mRecyclerView.scrollBy(0, top);
        } else {
            mRecyclerView.scrollToPosition(n);
        }

    }

    /**
     * 请求评论列表
     * */
    class LoadCollListInfo extends AsyncTask<String,Void,Boolean>{

        @Override
        protected Boolean doInBackground(String... params) {
            try{
                mData.clear();
                JsonObject jsonObject = HttpUtil.getResposeJsonObject(User.getCByAlbId(params[0],"2"));
                String flag = jsonObject.get("flag").getAsString();
                JsonArray colllist = jsonObject.get("collList").getAsJsonArray();
                for(JsonElement element : colllist){
                    mData.add(MainApplication.gsonInstance().fromJson(element,CollBean.class));
                }
                return true;
            }catch(Exception e){
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            netDailog.show();
        }

        @Override
        protected void onPostExecute(Boolean comlete) {
            netDailog.dismiss();
            if(comlete) {
                adapter.setData(mData);
                adapter.notifyDataSetChanged();
            }
        }

        public void cancleTask(){
            cancel(true);
            RequestThreadPool.finish();
        }
    }
}
